<template>
    <div class="layout">
        <Header v-if="!tableTotal" />
        <div class="container">
            <ZWGroup
                ref="GroupingRef"
                :type="14"
                :group-id="group_id"
                :auth-code="authCode"
                :get-group-fun="handleGetGroupList"
                @submit="handleGroupSubmit" />
            <div class="container_right">
                <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="initial"
                    :option="tableOption"
                    :row-key="getRowKey"
                    :fetch-params="state.searchParams"
                    :fetch-api="fetchApi()"
                    :close-loading="true"
                    @select="onSelect"
                    @selection-change="onSelectionChange"
                    @select-all="onSelectAll">
                    <template #headerOperate>
                        <el-button
                            v-auth="'BATCH_DOWN_LOAD'"
                            plain
                            :disabled="checkList.length == 0"
                            @click="onChange(3)">
                            批量下载
                        </el-button>
                        <el-button v-auth="'BATCH_DEL'" plain :disabled="checkList.length == 0" @click="onChange(0)">
                            批量删除
                        </el-button>
                        <el-button v-auth="'ADD'" type="primary" @click="toCreateActivity">新建活动</el-button>
                    </template>
                </ZwTable>
            </div>
        </div>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SMART_MARKETING_RED_ENVELOPES' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import Header from './components/Header.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import { mul } from '@/utils/math';
import { getpullList, pullChange, pullDown, pullDel } from '@/api/smartMarketing/redEnvelopes';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { groupInfo } from '@/api/smartMarketing/drainage/channelCode/index';
import { ref, reactive, computed, nextTick, onActivated } from 'vue';
import { getGroupList } from '@/api/concreation';
import { getCreateList } from '@/api/common';
import { isCachePage } from '@/utils/utils';

import { useStore } from '@/store';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { StatusColor, DOWLOAD_FILE } from '@/utils/smartMarketing';
import { endLoading, startLoading } from '@/utils/request';

const DeletdialogRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const store = useStore();
const GroupingRef: any = ref(null);
const isShow = ref(0);
const checkList = ref([]);
const delId = ref('');
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const group_id = ref<string>('all');
const defaultParams = {
    group_id: 'all',
    activity_name: '', //活动标题
    created_uid: '', //创建人id
    activity_status: 0, //活动状态 0-全部 1-未开始 2-进行中 3-已结束 4-提前结束
    create_at: [] //创建时间
};

// 分组权限code码
const authCode = {
    add: 'ADD_CHILD_GROUP',
    edit: 'EDIT_CHILD_GROUP',
    del: 'DEL_CHILD_GROUP'
};
const handleGroupSubmit = (v: any) => {
    router.push({
        path: '/smartMarketing/drainage/redEnvelopes',
        query: { group_id: v.id }
    });
    group_id.value = v.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value.clearSelection();
};
// 二次包装处理分组接口方法，拿取总数判断头部是否显示
const handleGetGroupList = async (data: any) => {
    const res = await getGroupList(data);
    tableTotal.value = res.total;
    return res;
};

// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const tableRef: any = ref<HTMLElement | null>(null);
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};

const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '活动搜索',
            name: 'activity_name',
            value: '',
            type: 'input',
            placeholder: '请输入活动标题/描述'
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '活动状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: 0 },
                        { name: '未开始', id: 1 },
                        { name: '进行中', id: 2 },
                        { name: '已结束', id: 3 },
                        { name: '提前结束', id: 4 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    tableRef.value.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), ...v, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v: any) => {
    tableRef.value.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const onDownload = async (row: any) => {
    const res = await pullDown({ activity_id: [row.id] });
    DOWLOAD_FILE(res.url, res.name);
    // tableRef.value.clearSelection();
};
const onBtn = (row: any) => {
    switch (row.activity_status) {
        case 1: // 未开始
            return (
                <>
                    <ElButton
                        size="small"
                        v-auth="LOOK"
                        onClick={() => {
                            router.push({
                                path: '/smartMarketing/drainage/redEnvelopes/detail',
                                query: { type: 'look', id: row.activity_id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="SWITCH"
                        onClick={() => {
                            delId.value = row.activity_id;
                            onChange(5);
                        }}>
                        开始
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="EDIT"
                        onClick={() => {
                            router.push({
                                path: '/smartMarketing/drainage/redEnvelopes/detail',
                                query: { type: 'edit', id: row.activity_id }
                            });
                        }}>
                        编辑
                    </ElButton>
                    <ElButton size="small" v-auth="DOWN_LOAD" onClick={() => onDownload(row)}>
                        下载
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="COPY_LINK"
                        onClick={async () => {
                            onCopy(row.activity_url);
                        }}>
                        复制
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="DEL"
                        onClick={() => {
                            delId.value = row.activity_id;
                            onChange(4);
                        }}>
                        删除
                    </ElButton>
                </>
            );
        case 2: // 进行中
            return (
                <>
                    <ElButton
                        size="small"
                        v-auth="LOOK"
                        onClick={() => {
                            router.push({
                                path: '/smartMarketing/drainage/redEnvelopes/detail',
                                query: { type: 'look', id: row.activity_id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="PARTICIPANT"
                        onClick={() => {
                            router.push({
                                path: '/smartMarketing/drainage/redEnvelopes/participant',
                                query: { id: row.activity_id }
                            });
                        }}>
                        参与者明细
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="STATISTICS"
                        onClick={() => {
                            router.push(`/smartMarketing/drainage/redEnvelopes/statistics?id=${row.activity_id}`);
                        }}>
                        统计
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="SWITCH"
                        onClick={() => {
                            delId.value = row.activity_id;
                            onChange(6);
                        }}>
                        结束
                    </ElButton>
                    <ElButton size="small" v-auth="DOWN_LOAD" onClick={() => onDownload(row)}>
                        下载
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="COPY_LINK"
                        onClick={async () => {
                            onCopy(row.activity_url);
                        }}>
                        复制
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="DEL"
                        onClick={async () => {
                            delId.value = row.activity_id;
                            onChange(4);
                        }}>
                        删除
                    </ElButton>
                </>
            );
        case 3: // 已结束
        case 4: // 提前结束
            return (
                <>
                    <ElButton
                        size="small"
                        v-auth="LOOK"
                        onClick={() => {
                            router.push({
                                path: '/smartMarketing/drainage/redEnvelopes/detail',
                                query: { type: 'look', id: row.activity_id }
                            });
                        }}>
                        查看
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="PARTICIPANT"
                        onClick={() => {
                            router.push({
                                path: '/smartMarketing/drainage/redEnvelopes/participant',
                                query: { id: row.activity_id }
                            });
                        }}>
                        参与者明细
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="STATISTICS"
                        onClick={() => {
                            router.push(`/smartMarketing/drainage/redEnvelopes/statistics?id=${row.activity_id}`);
                        }}>
                        统计
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="DEL"
                        onClick={async () => {
                            delId.value = row.activity_id;
                            onChange(4);
                        }}>
                        删除
                    </ElButton>
                </>
            );
    }
};

// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        minWidth: 130
    },
    {
        prop: 'qr_code_link',
        label: '二维码',
        align: 'center',
        minWidth: 100,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <>
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        src={row.qr_code_link}
                        style="width: 48px; height: 48px; font-size: 49px"
                        vSlots={{ error: slotError }}
                    />
                </>
            );
        }
    },
    {
        prop: 'red_type',
        label: '红包类型',
        width: 100,
        render({ row, column, index }) {
            return row.red_type == 1 ? '普通红包' : '拼手气红包';
        }
    },
    {
        prop: 'total_amount',
        label: '投放金额',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    {row.red_type == 1 ? (
                        <span>￥{row.total_amount}</span>
                    ) : (
                        <div>
                            ￥{mul(row.min_amount, row.red_num)}-{mul(row.max_amount, row.red_num)}
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'activity_status',
        label: '状态',
        width: 100,
        align: 'center',
        render({ row, column, index }) {
            return (
                <span style={StatusColor(row.activity_status, 'obj')?.color}>
                    {StatusColor(row.activity_status, 'obj')?.name}
                </span>
            );
        }
    },
    {
        prop: 'user_list',
        label: '引流成员',
        width: 200
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 100
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 100
    },
    {
        prop: 'activity_time',
        label: '有效期',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <p>{row.activity_time[0]}</p>
                            <p>至</p>
                            <p>{row.activity_time[1]}</p>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getpullList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.activity_id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.activity_id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};

const onChange = (num: number) => {
    switch (num) {
        case 0:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确认删除所选活动吗？';
            break;
        case 3:
            DeletdialogRef.value.appDialog.title = '下载提醒';
            DeletdialogRef.value.content = '确认下载所选活动吗？';
            break;
        case 4:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确认删除所选活动吗？';
            break;
        case 5:
            DeletdialogRef.value.appDialog.title = '开始提醒';
            DeletdialogRef.value.content = '确认开始当前活动吗？';
            break;
        case 6:
            DeletdialogRef.value.appDialog.title = '结束提醒';
            DeletdialogRef.value.content = '确认结束当前活动吗？';
            break;
    }
    isShow.value = num;
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    startLoading();
    try {
        switch (isShow.value) {
            case 0:
                await pullDel({ activity_id: checkList.value });
                ElMessage.success('删除成功');
                DeletdialogRef.value.appDialog.visible = false;
                // tableRef.value.reload()
                checkList.value = [];
                // GroupingRef.value.getGroup()
                await GroupingRef.value.getGroup(14);
                state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
                break;
            case 3:
                // eslint-disable-next-line no-case-declarations
                const res = await pullDown({ activity_id: checkList.value });
                DOWLOAD_FILE(res.url, res.name);
                ElMessage.success('活动下载成功');
                DeletdialogRef.value.appDialog.visible = false;
                break;
            case 4:
                await pullDel({ activity_id: [delId.value] });
                ElMessage.success('删除成功');
                DeletdialogRef.value.appDialog.visible = false;
                await GroupingRef.value.getGroup(14);
                state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
                // GroupingRef.value.getGroup()
                // tableRef.value.reload()
                break;
            case 5:
                await pullChange({ activity_id: delId.value, status: 1 });
                ElMessage.success('活动开始成功');
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                break;
            case 6:
                await pullChange({ activity_id: delId.value, status: 2 });
                ElMessage.success('活动结束成功');
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                break;
        }
        tableRef.value.clearSelection();
    } catch (error) {
        endLoading();
    }
};
const tableTotal = ref(0);

// 新增活动
const toCreateActivity = () => {
    router.push({
        path: '/smartMarketing/drainage/redEnvelopes/detail',
        query: { group_id: group_id.value == 'all' ? 0 : group_id.value }
    });
};
onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await GroupingRef.value.getGroup(14);
        }
        tableRef.value.clearSelection();
        // state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value, group_id: GroupingRef.value.selectId }
        GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
</script>

<style lang="scss" scoped>
.layout {
    height: calc(100vh - 142px);
    display: flex;
    flex-direction: column;

    .container {
        flex: 1;
        display: flex;
        overflow: hidden;

        .container_right {
            flex: 1;
            padding: 24px;
            box-sizing: border-box;
            background: #fff;
            border: 1px solid #eaeaea;
            overflow: hidden;
            display: flex;
            flex-direction: column;

            .zw-table {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;

                :deep(.el-table) {
                    flex: 1;

                    .el-table__empty-block {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }
        }
    }
}
</style>
